
using UnityEngine;

public class LongNoteConnector : MonoBehaviour
{
    public NoteObject noteObjectPre;
    public NoteObject noteObjectPost;
    public Transform preTrans;
    public Transform postTrans;

    private Transform quad; 
    public float width = 1.5f;

    void Awake()
    {
        quad = transform.Find("Quad");
        if (quad == null)
            Debug.LogError("Quad Not Found");
    }

    void LateUpdate()
    {
        if (preTrans != null && postTrans != null && quad != null)
        {
            quad.gameObject.SetActive(true);

            Vector3 worldStart = preTrans.position;
            Vector3 worldEnd = postTrans.position;

            Vector3 direction = (worldEnd - worldStart).normalized;
            float extraLength = 0.1f;
            worldStart -= direction * extraLength;
            worldEnd += direction * extraLength;
            Vector3 start = quad.InverseTransformPoint(worldStart);
            Vector3 end = quad.InverseTransformPoint(worldEnd);

            Vector3 side = Vector3.Cross((end - start).normalized, Vector3.forward).normalized * width * 0.5f;

            Vector3[] vertices = new Vector3[4];
            vertices[0] = start + side;
            vertices[1] = start - side;
            vertices[2] = end - side;
            vertices[3] = end + side;

            MeshFilter mf = quad.GetComponent<MeshFilter>();
            if (mf == null)
            {
                return;
            }

            Mesh mesh = mf.mesh;
            mesh.vertices = vertices;
            mesh.triangles = new int[] { 0, 1, 2, 2, 3, 0 };
            mesh.uv = new Vector2[]
            {
            new Vector2(0,1),
            new Vector2(0,0),
            new Vector2(1,0),
            new Vector2(1,1)
            };
            mesh.RecalculateNormals();
        }
        else if (quad != null)
        {
            quad.gameObject.SetActive(false);
        }
    }
    public void Initialize(NoteObject a, NoteObject b)
    {
        noteObjectPre = a;
        noteObjectPost = b;
        preTrans = a.transform;
        postTrans = b.transform;
    }

    public void Initialize(NoteObject pre, Transform top)
    {
        noteObjectPre = pre;
        preTrans = pre.transform;
        postTrans = top;
    }

    public void DestoryLongNote()
    {
        noteObjectPre = null;
        noteObjectPost = null;
        preTrans = null;
        postTrans = null;
        quad = null;
        Destroy(gameObject);
    }
}